from datetime import datetime
import os
import tempfile
import uuid
from django.views.decorators.csrf import csrf_exempt
from django.views.decorators.http import require_http_methods
import redis
import requests
from reportservice.helpers import ApiResponse
import json
from .yida_config import YidaClient
from yida_app_service.models import JgData
from yida_app_service.utils.common_utils import timestamp_ms_to_date
from django.db import transaction
from doc_service.utils import merge_pdfs
from oss_service.views import bucket
from shutil import rmtree
import time
import logging
yida_client = YidaClient()
logger = logging.getLogger(__name__)
# org_id = "0D30B9A789B6454CBCAAF80380CB9809"
admin_user_id = "014835331124251186"
r = redis.StrictRedis(host='10.8.0.83', port=6379, db=0)

contract_form_id = "FORM-50450F2F696E467DAF0A99C15BF62A5AROMB"
wt_form_id = "FORM-2CE1B37D96B64E24A0C6659C5FA7F25BDJW3"
jg_test_form_id ="FORM-A0B90C1F66044A19B7E4C9A087CA6C6BH8MS"
report_form_id = "FORM-686A7975279942B692D9C82E4D5FAE31YP3M"
billing_apply_form_id  = "FORM-24BB749E5D744FBDBE5107738ECA04258LF0"
company_name = "dingfeng"




@csrf_exempt
@require_http_methods(['POST'])
def batch_create_wt(request):
    try:
        req_data = json.loads(request.body)
        form_inst_id = req_data.get('form_inst_id')
        form_uuid = req_data.get('form_uuid')
        wt_type = req_data.get('wt_type')
        wt_count = int(req_data.get('wt_count')) - 1
        process_code = req_data.get('process_code')
        admin_user_id = req_data.get('admin_user_id')

        if not (form_inst_id and form_uuid and process_code):
            return ApiResponse.fail("必要的表单信息缺失。")

        yida_instance = yida_client.get_form_items_by_ids(form_uuid, form_inst_id, admin_user_id)
        form_data = yida_instance[0].form_data
        water_number = int(form_data.get("numberField_lutjluh9"))
        gc_info = json.loads(json.loads(form_data.get("associationFormField_lqqbd27d_id")))[0]
        max_retries = 3

        # 创建工具函数
        def update_form_data(wt_number, yp_number):
            return {
                **form_data,
                "numberField_lutjluh9": water_number,
                "textField_lqqbd279": wt_number,
                "textField_lqqbd27b": wt_number,
                "textField_lqqbd27a": yp_number,
                "radioField_lz2agi63": "是",
                "textField_lutjluha": str(uuid.uuid4()),
                "employeeField_lyxzlrkg": [form_data["employeeField_lyxzlrkg_id"][0]],
                "employeeField_lzgmxlgm":[form_data["employeeField_lzgmxlgm_id"][0]],
                "associationFormField_lqqbd27d": [gc_info],
                "numberField_lzdv1qkq":1,
            }

        def create_instance(wt_number, yp_number):
            retries = 0
            while retries < max_retries:
                try:
                    form_update = update_form_data(wt_number, yp_number)
                    yida_client.create_process_instance(form_uuid, admin_user_id, form_update, process_code)
                    return True
                except Exception as e:
                    logger.error(f"创建委托{wt_number}失败，重试次数：{retries}，错误：{str(e)}")
                    retries += 1
                    time.sleep(1)
            logger.info(f"委托编号 {wt_number} 创建失败，已达到最大重试次数。")
            return False

        # 主逻辑区分
        if wt_type == "多份委托":
            for i in range(wt_count):
                report_code = form_data.get("textField_lz0xuukr")
                water_number += 1
                wt_number = f"{report_code}{water_number:04}"
                yp_number = wt_number + "01"

                if not create_instance(wt_number, yp_number):
                    return ApiResponse.fail(f"委托编号 {wt_number} 创建失败")
            return ApiResponse.success(message="批量创建多份委托成功")

        elif wt_type == "多份样品":
            wt_number = form_data.get("textField_lqqbd279")
            for i in range(wt_count):
                index = i + 2
                yp_number = f"{wt_number}{index:02}"

                if not create_instance(wt_number, yp_number):
                    return ApiResponse.fail(f"样品编号 {yp_number} 创建失败")
            return ApiResponse.success(message="批量创建多份样品成功")

    except json.JSONDecodeError:
        return ApiResponse.fail("JSON格式错误")
    except Exception as e:
        logger.error(f"处理请求时发生错误：{str(e)}")
        return ApiResponse.fail("服务器内部错误")